package com.example.gatewaytest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class CustomGatewayFilterFactory extends AbstractGatewayFilterFactory<CustomConfig> implements Ordered {
    private static final Logger log = LoggerFactory.getLogger(CustomGatewayFilterFactory.class);

    public CustomGatewayFilterFactory() {
        super(CustomConfig.class);
    }

    @Override
    public GatewayFilter apply(CustomConfig config) {
        return new GatewayFilter() {
            /*
             * 自定义网关过滤器
             * ServerWebExchange  服务器Web交换对象 类似于ServletRequest 和ServletResponse
             * GatewayFilterChain  网关过滤器链
             * Mono<Void>  表示异步操作完成时返回的空值
             */
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                //pre 类型  执行请求  post类型
                log.info("Pre Filter,config={}", config);  //Pre 类型 过滤器代码逻辑
                return chain.filter(exchange).then(Mono.fromRunnable(() -> log.info("Post Filter")));
            }
        };
    }

    @Override
    public int getOrder() {
        return LOWEST_PRECEDENCE;
    }
}
